<template>
  <canvas
    ref="particle"
    v-bind="$attrs"
  ></canvas>
</template>
<script>
import Particle from '@/lib/js/utils/particle'

export default {
  props: {
    redraw: {
      type: Boolean,
      default: false
    },
    backgroundColor: {
      type: String,
      default: ''
    },
    colors: {
      type: Array,
      default: undefined
    },
    types: {
      type: [Array, Number],
      default: undefined
    },
    shapes: {
      type: [Array, Number],
      default: undefined
    }
  },
  data() {
    return {
      particle: null
    }
  },
  watch: {
    redraw: {
      handler(bool){
        if (!bool) {
          return this.particle && this.particle.destory()
        }
        if (this.particle) {
          this.particle.draw()
        } else {
          this.$nextTick(() => {
            const {
              backgroundColor, colors, types, shapes
            } = this
            this.particle = new Particle(this.$refs.particle, {
              backgroundColor,
              colors,
              types,
              shapes,
              animationEnd: () => {
                this.$emit('animationend')
              }
            })
          })
        }
      },
      immediate: true
    }
  },
  beforeUnmount() {
    this.particle && this.particle.destory()
    this.particle = null
  }
}
</script>
